package main

import (
	"gitee.com/ling-bin/network/Receivers"
	"gitee.com/ling-bin/network/netClient"
	"gitee.com/ling-bin/network/netInterface"
	"log"

	"fmt"
	"time"
)

//
func main() {
	for i := 0; i < 4096; i++ {
		go start()
	}
	select {}
}

func start() {
	config := netClient.DefaultConfig("udp", "192.168.1.24:7018")
	client := netClient.NewClient(config)
	client.SetOnReceive(Receive)
	client.SetOnConnStart(func(connection netInterface.IConnection) {
		log.Println("连接成功！")
	})
	client.SetOnConnStop(func(connection netInterface.IConnection) {
		log.Println("连接断开！")
	})
	//加入分包逻辑
	client.SetHandleStrategy(func(connection netInterface.IConnection, bytes []byte) *netInterface.StrategyData {
		receiver := make([]netInterface.IReceiver, 0, 2)
		receiver = append(receiver, Receivers.NewSpliceSymbolReceiver(0x28, 0x29))
		return &netInterface.StrategyData{
			Key: "",
			Receivers: receiver,
		}
	})
	//设置日志处理
	client.SetLogHandle(func(level netInterface.ErrLevel, msg string) {
		switch level {
		case netInterface.Fatal:
			log.Println("[致命]", msg)
			break
		case netInterface.Error:
			log.Println("[致命]", msg)
			break
		case netInterface.Warn:
			log.Println("[警告]", msg)
			break
		case netInterface.Info:
			log.Println("[消息]", msg)
			break
		}
	})
	_, err := client.Connect()
	if err == nil {
		//go SendData(client)
		client.SendData([]byte("(client)"), "")
	} else {
		log.Println("连接异常：", err)
	}
	select {}
}

//定时发送数据
func SendData(client netClient.IClient) {
	for {
		client.SendData([]byte("(client)"), "")
		time.Sleep(time.Second)
	}
}

//数据接收
func Receive(connection netInterface.IConnection, data []byte) {
	fmt.Println("接收数据:", string(data))
	fmt.Println("心跳时间：", connection.GetHeartTime().Format("2006-01-02 15:04:05"))
	fmt.Println("接收信息：")
	fmt.Println(connection.GetRecInfo())
	fmt.Println("发送信息：")
	fmt.Println(connection.GetRepInfo())
}
